package com.ketangpai.admin.exception;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ketangpai.admin.utils.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理器
 */
@ControllerAdvice//定义全局异常处理类,默认只会处理controller层抛出的异常
public class GlobalExceptionHandler {

    @ExceptionHandler//指明需要处理的异常类型以及子类。注解放在方法上面。
    @ResponseBody
    public JsonResult<?> handle(BusinessException e){
        return JsonResult.error(e.getMessage());
    }

    @ExceptionHandler(TokenExpiredException.class) // 假设 Token 过期会抛出这个自定义异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<String> handleTokenExpiredException(TokenExpiredException ex) {
        return new ResponseEntity<>("Token has expired", HttpStatus.UNAUTHORIZED);
    }
}
